package dk.degofedal.scala.math.numerical

class Bisection {

	type T = Double
	val diff = 1e-8
	
	def solve(a: T, b: T)(f: (T) => T) : (T, Int) = {
		
		def solveInner(a: T, b: T, i: Int)(f: (T) => T) : (T, Int) = {
			val x = (a + b) / 2.0
			val f_x = f(x)
			
			if(Math.abs(f_x) < diff) {
				(x, i)
			} else {
				val f_a = f(a)
				if(f_a * f_x < 0){
					solveInner(a,x,i+1)(f)
				} else {
					solveInner(x,b,i+1)(f)
				}
			}
		}
		
		require(f(a) * f(b) < 0)
		
		solveInner(a,b,0)(f) 
	}
	
}